package com.cruel_wandering.wifi_geo_predictor;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class Logger
  implements SharedPreferences.OnSharedPreferenceChangeListener
{
	static private final String TAG = "Logger";

	static private Logger instance = null;

	private boolean debugMode;

	private Logger(boolean debugMode)
	{
		this.debugMode = debugMode;
	}

	public static Logger getInstance(Context ctx)
	{
		if (instance == null)
		{
			Log.v(TAG, "Creating new instance of Logger");
			SharedPreferences prefs =
				PreferenceManager.getDefaultSharedPreferences(ctx);

			instance = new Logger(prefs.getBoolean(Preferences.DEBUG_MODE, false));
			PreferenceManager.getDefaultSharedPreferences(ctx)
			  .registerOnSharedPreferenceChangeListener(instance);
		}
		return instance;
	}

  public void log(String tag, String msg)
  {
  	if (!debugMode)
  		return;
  	
  	Log.v(tag, msg);
  }

  static private boolean isDebugMode(Context ctx)
  {
	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx);

    return sp != null ? sp.getBoolean(Preferences.DEBUG_MODE, true) : false;
  }

  static public void toast(Context ctx, String msg)
  {
    if (!isDebugMode(ctx))
      return;

    Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
  }

  static public void logAndToast(Context ctx, String tag, String msg)
  {
    toast(ctx, msg);
    getInstance(ctx).log(tag, msg);
  }

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
    String key)
  {
		if (!Preferences.DEBUG_MODE.equals(key))
			return;

		debugMode = sharedPreferences.getBoolean(key, false);
		Log.d("Logger", "debug_mode = " + debugMode);
	}
}